package main

import (
	"fmt"
	"sync"
	"time"
)

// 生产者：向通道发送数据
func producer(ch chan<- int, wg *sync.WaitGroup) {
	for i := 0; i < 5; i++ {
		fmt.Println("发送:", i)
		ch <- i
		time.Sleep(time.Second)
	}
	wg.Done()
	close(ch)
}

// 消费者：从通道接收数据
func consumer(ch <-chan int, wg *sync.WaitGroup) {
	wg.Done()
	for value := range ch {
		fmt.Println("接收到:", value)
	}
}

func main() {
	ch := make(chan int)

	var wg sync.WaitGroup

	wg.Add(1)
	go producer(ch, &wg) // 启动生产者goroutine
	wg.Add(1)
	go consumer(ch, &wg) // 启动消费者goroutine

	// 等待一段时间以确保所有操作完成
	wg.Wait()
}
